package App.Controller;

import App.Model.Contact_Message;
import App.Model.UserData;
import App.Public.controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;

import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

public class EditController extends AddContactController{
    @FXML private VBox ROOT;
    //group和username在mainViewController里调用Contact_Message的含参构造器时set了↓↓↓↓↓
    private Contact_Message contactNow = (Contact_Message)(controller.DATA.getData("ContactNow"));

    public EditController() throws Exception {}

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        loadCss(ROOT,"edit.css");
        picture_Contact.setImage(new Image(String.valueOf(getResource("Image/Contacts_icon.png"))));

        text_GivenName.textProperty().addListener( (event)->{
            label_showName.setText("显示名字为："+text_GivenName.getText()+text_FirstName.getText());
        });

        text_FirstName.textProperty().addListener( (event)->{
            label_showName.setText("显示名字为："+text_GivenName.getText()+text_FirstName.getText());
        });

        try {
            Contact_Message contactNow = (Contact_Message) controller.DATA.getData("ContactNow");
            setData(contactNow);
            if (contactNow.getPicture() != null)
                picture_Contact.setImage(new Image(contactNow.getPicture().toString()));
        } catch (Exception e) { e.printStackTrace(); }

//        ArrayList<Window> windowList = null;
//        try {
//            windowList = (ArrayList<Window>) controller.DATA.getData("windowList");
//        } catch (Exception e) {}
//        windowList.add(button_Cancel.getScene().getWindow());

    }

    public void setData(Contact_Message contactNow) throws Exception {
        text_GivenName.setText(contactNow.getGiveName());
        text_FirstName.setText(contactNow.getFirstName());
        text_Remark.setText(contactNow.getRemark());
        comboBox_Sex.setValue(contactNow.getSex());
        text_Birthday.setText(contactNow.getBirthday());
        text_QQ.setText(contactNow.getQQ());
        text_PetName.setText(contactNow.getPetName());
        text_Website.setText(contactNow.getWebsite());
        text_Country_Home.setText(contactNow.getCountry_Home());
        text_Province_Home.setText(contactNow.getProvince_Home());
        text_City_Home.setText(contactNow.getCity_Home());
        text_Street_Home.setText(contactNow.getStreet_Home());
        text_PostCode_Home.setText(contactNow.getPostCode_Home());
        text_Company.setText(contactNow.getCompany());
        text_Department.setText(contactNow.getDepartment());
        text_Job.setText(contactNow.getJob());
        text_Fax.setText(contactNow.getFax());
        text_Country_Company.setText(contactNow.getCountry_Company());
        text_Province_Company.setText(contactNow.getProvince_Company());
        text_City_Company.setText(contactNow.getCity_Company());
        text_Street_Company.setText(contactNow.getCity_Company());
        text_PostCode_Company.setText(contactNow.getPostCode_Company());
        //根据contactNow中存放的电话自动添加电话项
        int i = 1;
        for(String phone : contactNow.getPhoneNumberList()){
            if (i>1) //要是计数君记下的电话是多个，则添加新电话项
                addPhoneAuto(phone);
            else //否则不添加新的电话项直接在原电话项添加
                text_PhoneNumber.setText(phone);
            i++;
        }
        //根据contactNow中存放的邮箱自动添加Email项
        i = 1;
        for(String email : contactNow.getEmailList()){
            if (i>1) //要是计数君记下的Email是多个，则添加新Email项
                addEmailAuto(email);
            else //否则不添加新的Email项直接在原Email项添加
                text_Email.setText(email);
            i++;
        }
        //初始化头像
        if (contactNow.getPicture() != null)
            picture_Contact.setImage(new Image(contactNow.getPicture().toString()));
    }

    public void addEmailAction(ActionEvent actionEvent) throws Exception {
        vBox_Email.getChildren().add(new PhoneAddPanel());
    }

    /**
     * 在Email的vBox中添加Email项
     * @param phoneNumber 所添加的Email
     * @throws Exception
     */
    public void addPhoneAuto(String phoneNumber) throws Exception {
        FlowPane panel = new PhoneAddPanel();
        vBox_Phone.getChildren().add(panel);
        for(Node node :panel.getChildren()){
            if (node instanceof TextField){
                ((TextField) node).setText(phoneNumber);
            }
        }
    }

    /**
     * 在Email的vBox中添加Email项
     * @param email 所添加的Email
     * @throws Exception
     */
    public void addEmailAuto(String email) throws Exception {
        FlowPane panel = new PhoneAddPanel();
        vBox_Email.getChildren().add(panel);
        for(Node node :panel.getChildren()){
            if (node instanceof TextField){
                ((TextField) node).setText(email);
            }
        }
    }

    public void removeAction(ActionEvent actionEvent) throws Exception {
        ListView<String> groupList = (ListView<String>) controller.DATA.getData("groupList");
        ListView<String> contactList = (ListView<String>) controller.DATA.getData("contactList");
        TableView<TableData> table = (TableView<TableData>) controller.DATA.getData("table");
        UserData user = (UserData) controller.DATA.getData("userData");
        Contact_Message selectedPerson = table.getSelectionModel().getSelectedItem().getPerson();
        //在所有分组删除

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION); //对话框
        alert.setTitle("删除联系人");
        alert.setContentText(selectedPerson.getFullName()+"将在所有联系人删除");
        alert.setHeaderText(null);
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK){
            //用户选择OK后的事件
            user.removePerson(selectedPerson);
            cancelAction(new ActionEvent());
        }

        //删除完成后会跳到所有人的选项，相当于刷新
        String groupName = groupList.getSelectionModel().getSelectedItems().toString();
        groupList.getSelectionModel().select(groupName);

        table.getItems().clear();
//        if (groupName.isEmpty() || groupName == null){
            contactList.getSelectionModel().select("所有联系人");
            table.getItems().addAll(TableData.getDataList(user.getPersonBase()));
//        }
//        else {
//            groupList.getSelectionModel().select(groupName);
//            table.getItems().addAll(TableData.getDataList(user.getGroup(groupName).getGroup()));
//        }
    }

    public void saveAction(ActionEvent actionEvent) throws Exception {
        Contact_Message newContact = saveContact();

        if(newContact != null) {
            //若不为空，执行界面刷新
            TableView<TableData> table = (TableView<TableData>) controller.DATA.getData("table");

            table.getItems().set(table.getSelectionModel().getFocusedIndex(),new TableData(newContact));

            cancelAction(new ActionEvent());
        }
    }

    public Contact_Message saveContact() throws Exception{
        String textName = text_GivenName.getText() + text_FirstName.getText();
        textName = textName.replaceAll(" ","");
        if (textName.length() == 0){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("Warning");
            alert.setHeaderText("");
            alert.setContentText("未输入姓名！");
            alert.showAndWait();
            return null;
        }

        contactNow.setGiveName(text_GivenName.getText());
        contactNow.setFirstName(text_FirstName.getText());
        contactNow.setFullName(text_GivenName.getText() + text_FirstName.getText());

        //保存PhoneNumber
        contactNow.getPhoneNumberList().clear(); //先清空然后再加入要保存的PhoneNumber
        for (Node flowPaneIncludePhoneText : vBox_Phone.getChildren()) {
            FlowPane panel; //循环get到放置电话列表的VBox中放置每一个电话的flowPane
            panel = (FlowPane)flowPaneIncludePhoneText;
            for(Node control : panel.getChildren()){
                if (control instanceof TextField && !((TextField) control).getText().equals("")){
                    //循环找到放置电话的TextField并做储存到newContact对象的操作
                    contactNow.addPhoneNumber((((TextField) control).getText()));
                }
            }
        }

        //保存Email
        contactNow.getEmailList().clear(); //先清空然后再加入要保存的Email
        for (Node flowPaneIncludeEmailText : vBox_Email.getChildren()) {
            FlowPane panel; //循环get到放置Email列表的VBox中放置每一个电话的flowPane
            panel = (FlowPane)flowPaneIncludeEmailText;
            for(Node control : panel.getChildren()){
                if (control instanceof TextField && !((TextField) control).getText().equals("")){
                    //循环找到放置Email的TextField并做储存到newContact对象的操作
                    contactNow.addEmail((((TextField) control).getText()));
                }
            }
        }

        contactNow.setRemark(text_Remark.getText());
        if (comboBox_Sex.getSelectionModel().getSelectedItem() != null) {
            //若性别被选择了，则存放性别
            contactNow.setSex(comboBox_Sex.getSelectionModel().getSelectedItem().toString());
        }
        contactNow.setBirthday(text_Birthday.getText());
        contactNow.setPetName(text_PetName.getText());
        contactNow.setQQ(text_QQ.getText());
        contactNow.setWebsite(text_Website.getText());
        contactNow.setCountry_Home(text_Country_Home.getText());
        contactNow.setProvince_Home(text_Province_Home.getText());
        contactNow.setPostCode_Home(text_PostCode_Home.getText());
        contactNow.setStreet_Home(text_Street_Home.getText());
        contactNow.setCity_Home(text_City_Home.getText());
        contactNow.setProvince_Company(text_Province_Company.getText());
        contactNow.setCompany(text_Company.getText());
        contactNow.setCity_Company(text_City_Company.getText());
        contactNow.setCountry_Company(text_Country_Company.getText());
        contactNow.setStreet_Company(text_Street_Company.getText());
        //picture在addPicture监听器里set
        return contactNow;
    }
}
